import { Injectable } from '@nestjs/common';
import AlipaySdk from 'alipay-sdk';
import * as fs from 'fs';
import { ConfigService } from '../../config/config.service';
import AlipayFormData from 'alipay-sdk/lib/form';

@Injectable()
export class AlipayService {
  alipaySdk:AlipaySdk;
  alipayConfig:ConfigService;
  projectConfig:ConfigService;
  notifyUrl:string;
  constructor(){
    this.alipayConfig = new ConfigService('src/env/alipay.env');
    this.projectConfig = new ConfigService('src/env/project.env');
    this.notifyUrl=`${this.projectConfig.get('protocol')}://${this.projectConfig.get('ip')}:${this.projectConfig.get('port')}/api/alipay/notify`;
    this.alipaySdk = new AlipaySdk({
      appId: this.alipayConfig.get('appid'),
      privateKey: fs.readFileSync(this.alipayConfig.get('privateKey'), 'ascii'),
      alipayPublicKey:this.alipayConfig.get('alipayPublicKey'),
      gateway:this.alipayConfig.get('gateway'),
      signType:"RSA2",
    });
  }

  async tradePagePay(outTradeNo,totalAmount,subject,body){
    const formData = new AlipayFormData();
    // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
    formData.setMethod('get');
    formData.addField('notifyUrl', this.notifyUrl);
    formData.addField('bizContent', {
      outTradeNo: outTradeNo,
      productCode: "FAST_INSTANT_TRADE_PAY",
      totalAmount: totalAmount,
      subject: subject,
      body: body,
    });

    const result = await this.alipaySdk.exec(
      'alipay.trade.page.pay',
      {},
      { formData: formData },
    );
    return result
  }

  async tradeWapPay(outTradeNo,totalAmount,subject,body){
    const formData = new AlipayFormData();
    // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
    formData.setMethod('get');
    formData.addField('notifyUrl', this.notifyUrl);
    formData.addField('bizContent', {
      outTradeNo: outTradeNo,
      totalAmount: totalAmount,
      subject: subject,
      body: body,
      productCode:"QUICK_WAP_WAY",
      quitUrl:"https://www.baidu.com"
    });

    const result = await this.alipaySdk.exec(
      'alipay.trade.wap.pay ',
      {},
      { formData: formData },
    );
    return result
  }

  async checkNotify(body){
    return this.alipaySdk.checkNotifySign(body);
  }

  async tradePageRefund(outTradeNo,refundAmount,refundReason?){
    const formData = new AlipayFormData();
    // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
    formData.setMethod('get');
    formData.addField('notifyUrl', this.notifyUrl);
    formData.addField('bizContent', {
      outTradeNo: outTradeNo,
      refundAmount: refundAmount,
      refundReason: refundReason||'正常退款'
    });


    const result = await this.alipaySdk.exec(
      'alipay.trade.page.refund',
      {},
      { formData: formData },
    );
    return result
  }
}
